<template>
  <a-input
    :value="value"
    :placeholder="placeholder || t('placeholder-icon')"
    :allow-clear="allowClear"
    @update:value="(v) => (!v ? emit('update:value', null) : updateValue(v))"
  >
    <template #addonAfter>
      <a-popover
        v-model:open="open"
        :title="t('component-select-icon-title')"
        trigger="click"
        placement="right"
      >
        <template #content>
          <div class="icon-box">
            <div
              class="icon-item"
              v-for="icon in icons"
              :key="icon"
              @click="
                emit('update:value', icon);
                open = false;
              "
            >
              <component style="cursor: pointer" :is="icon" />
            </div>
          </div>
        </template>
        <SelectOutlined style="cursor: pointer" />
      </a-popover>
    </template>
    <template #prefix>
      <component :is="value" style="margin-right: 5px" />
    </template>
  </a-input>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import * as Icons from "@ant-design/icons-vue";
import { debounce } from "lodash";
interface Props {
  /**绑定值 */
  value: string;
  /**占位提示文字 */
  placeholder?: string;
  /**可清除 */
  allowClear?: boolean;
}
withDefaults(defineProps<Props>(), {
  allowClear: true,
});
const emit = defineEmits(["update:value"]);
const { t } = useI18n();
const open = ref(false);
const icons: string[] = Object.keys(Icons).filter(
  (key) => /[A-Z]/.test(key[0]) && key.endsWith("Outlined")
);
const updateValue = debounce((value: string) => {
  if (icons.includes(value)) {
    emit("update:value", value);
  } else {
    emit("update:value", null);
  }
}, 500);
</script>
<style lang="less" scoped>
.icon-box {
  width: 328px;
  height: 320px;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
  .icon-item {
    width: 40px;
    height: 40px;
    font-size: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    :first-child :hover {
      border: 1px solid #666666;
      padding: 4px;
      border-radius: 4px;
    }
  }
}
</style>
